package com.uni.utils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.*;

/**
 * --------------project-------------
 *
 * @Author Unirithe  - Mr.Chao
 * - CSDN:
 * https://blog.csdn.net/Unirithe
 * - GitHub:
 * https://github.com/unirithe
 * @create 2021/12/22 10:06
 * ------------------------------------------
 */
public class FileUtil {
    public static String read(HttpServletRequest req, String name){
        StringBuffer result = new StringBuffer();
        try {
            Part part = req.getPart(name);
            InputStream is = part.getInputStream();
            InputStreamReader ris = new InputStreamReader(is, "UTF-8");
            BufferedReader bfr = new BufferedReader(ris);
            String temp = "";
            if ((temp = bfr.readLine()) != null)
                result.append(temp);
            bfr.close();
            ris.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public static boolean saveFile(HttpServletRequest req, String path0, String path1){
        String path = path0 + path1;
        // 如果目录不存在则创建
        File uploadDir = new File(path0);
        try{
            if (!uploadDir.exists()) uploadDir.mkdir();
            Part part = req.getPart("form-publish-img");
            InputStream is = part.getInputStream();
            FileOutputStream fos = new FileOutputStream(path);
            byte[] bty = new byte[1024 * 10];
            int length =0;
            while((length=is.read(bty))!=-1){
                fos.write(bty,0,length);
            }
            fos.close();
            is.close();
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
